function [ll,grad,A,dAdpar] = T2ABCModel(par, x, echoes, sigma)

% computes the likelihood of the rice distributed inversion recovery data
% echoes = inversion times [n x 1] vector
% par = the 3 element parametervector [A, B, R1]
%
% The datamodel is given by
% M = A * exp (-B*TE) + C
% dM/dPar = {exp(-R2*TE, -TE*A*exp(-TE * R2), 1}
% B_0 = R2, echoes = TEs
%
% Created by Henk Smit, EMC, 01-2011 based on the work by Dirk Poot, University of Antwerp, 13-8-2007

if size(par,1) ~= 3% + (nargin<=3)  HENK
    error('incorrect parameter vector');
end;

if nargin <= 2
    echoes = x;
    ll=0;
    grad=0;
end
if nargin<=3
    sigma = 0; %HENK
end;

numgr = size(echoes,1); %numTEs
if ((size(x,1)~=numgr || size(x,2)~=1) && ~isempty(x)) %|| size(echoes,2)~=1  || numel(sigma)~=1
    error('incorrect size in input.');
end;

A_ex(:,1) = exp(-echoes(:)*par(2));
A(:,1) = par(1) * A_ex(:) + par(3);

dAdpar=[A_ex(:,1) -echoes.*A(:) ones(numgr,1)];

% if nargout>2
%     varargout(1) = A;
%     varargout(2) = dAdpar;
% end

if isempty(x)
    ll = A;
    return;
end;

if nargin>2
    [lrpdf, ricegrad] = logricepdf(x, A, sigma);
    dAdpar=[A_ex(:,1) -echoes.*A(:) ones(numgr,1)];
    grad = reshape(-sum( reshape( ricegrad(:,ones(1,3)).*dAdpar, numgr, 1 * 3) ), 1, 3);
    grad = grad';
    ll = - sum( lrpdf(:) );
    clear A;
    clear dAdpar;
% else
%     [lrpdf] = logricepdf(x, A, sigma );
%     ll = - sum( lrpdf(:) );
end;

